﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using BCCommon;
using BCCommon.Enums.Chats;
using BCDto.Chats.Message;
using BCDto.Chats.Thread;
using BCDto.MySql.Orders.Order;
using BCService;
using BCService.WebDomainService.AdminBelongAreaService;

namespace BlackCoffeeRESTful.Configs
{
    public class OrderPushService
    {
        private readonly IWebSocketContextService webSocketContextService;
        private readonly IRedisService redisService;
        private readonly IAdminBelongAreaService adminBelongAreaService;

        public OrderPushService(IWebSocketContextService webSocketContextService, IRedisService redisService, IAdminBelongAreaService adminBelongAreaService)
        {
            this.webSocketContextService = webSocketContextService;
            this.redisService = redisService;
            this.adminBelongAreaService = adminBelongAreaService;
        }

        public void Run()
        {
            this.redisService.Subscriber<OrderDto>(RedisChannelConfig.PushOrder, (channel, value) =>
            {
                OrderDto orderDto = JsonConvert.DeserializeObject<OrderDto>(value.ToString().Replace("{{", "{").Replace("}}", "}"));

                if (orderDto == null)
                {
                    return;
                }

                var messageDto = new MessageDto
                {
                    MessageId = -1,
                    ThreadId = -1,
                    MessageType = MessageType.RawData,
                    Content = "有新订单了。",
                    RawData = new
                    {
                        orderDto.IsAggregate,
                        orderDto.OrderAggregateId,
                        orderDto.OrderId,
                        orderDto.UserId
                    },
                    CreateTime = DateTime.Now,
                    CreateUser = new ThreadParticipantDto
                    {
                        UserId = "SYSTEM",
                        UserName = "系统",
                        AvatarUrl = "/assets/image/system.png"
                    }
                };

                string jsonString = JsonConvert.SerializeObject(messageDto, GeneralContainer.JsonSerializerSettings);

                foreach (var adminBelongArea in this.adminBelongAreaService.GetAllAsync(null, orderDto.ProvinceId, orderDto.CommunityId, null, null).Result)
                {
                    this.webSocketContextService.SendTextAsync(jsonString, $"ADMIN-{adminBelongArea.AdminId}");
                }
            });
        }
    }
}
